import 'package:flutter/material.dart';
import 'package:opene/app_constant.dart';
import 'package:opene/app_theme.dart';
import 'package:opene/app_utils.dart';
import 'package:opene/base/base_state.dart';
import 'package:opene/base/commentdialogscreen.dart';
import 'package:opene/base/loading.dart';
import 'package:opene/base/scan_code.dart';
import 'package:opene/net/network_manager.dart';
import 'package:opene/net/response/base_response.dart';
import 'package:opene/ui/fbapick/fbapickcategoryscreen.dart';
import 'package:opene/ui/fbapick/fbapickmodel.dart';
import 'package:toast/toast.dart';

class FBAPickScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return FBAPickScreenPage();
  }
}

class FBAPickScreenPage extends StatefulWidget {
  @override
  _FBAPickPageState createState() => _FBAPickPageState();
}

class _FBAPickPageState extends BaseState<FBAPickScreen> {
  List<FBAPick> data = new List();

  @override
  String setTitle({String title}) {
    return !Utils.isEmpty(title) ? title : "Pick";
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    setLayoutBottomContentGone();
    Future.delayed(Duration(milliseconds: 300), () {
      setState(() {
        getContainerNoList();
      });
    });
  }

  void didPopNext() {
    setState(() {
      // 这里刷新页面状态
    });
  }

  @override
  Widget getViewBinding() {
    return Padding(
      padding: const EdgeInsets.only(left: 0, top: 10, right: 0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            margin: const EdgeInsets.only(left: 15, top: 0, right: 15, bottom: 0),
            width: double.infinity,
            child: ConstrainedBox(
              constraints: BoxConstraints(maxHeight: 35),
              child: TextField(
                controller: textEditingController,
                textInputAction: TextInputAction.search,
                onSubmitted: (String text) {
                  print('Searching for $text');
                  if (Utils.isEmpty(text)) {
                    return;
                  }
                  checkContainerNo(text);
                },
                // autofocus: true,
                decoration: InputDecoration(
                  suffixIcon: IconButton(
                    padding: EdgeInsets.all(2.0),
                    icon: Icon(
                      Icons.qr_code_scanner,
                      size: 28,
                      color: MyAppTheme.nearlyBlue,
                    ),
                    onPressed: () {
                      // requestPermissions();
                      // Utils.scanBarcode(context);
                      Navigator.of(context).push(MaterialPageRoute(builder: (context) {
                        return ScanCode();
                      })).then((text) {
                        if (text == null) {
                          return;
                        }
                        setState(() {
                          textEditingController.text = text;
                        });
                        print(text); //拿到扫描结果
                        checkContainerNo(text);
                      });
                    },
                  ),
                  border: OutlineInputBorder(
                    borderSide: BorderSide(
                      color: MyAppTheme.nearlyBlue,
                    ),
                    borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                  ),
                  enabledBorder: OutlineInputBorder(
                    borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                    // 设置焦点之外的边框颜色
                    borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                    // 设置焦点时的边框颜色
                    borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                  ),
                  hintText: "scan or input pickNo",
                  filled: true,
                  fillColor: MyAppTheme.white,
                  //隐藏下划线
                  //border: InputBorder.none,
                  hintStyle: TextStyle(color: Colors.grey),
                  contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 15),
                ),
                onChanged: (text) {
                  code = text;
                },
              ),
            ),
          ),
          Container(
            margin: EdgeInsets.only(left: 15, top: 5, bottom: 5),
            child: Text(
              "Pending Jobs",
              style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
            ),
          ),
          Expanded(
            child: setListView(),
          ),
        ],
      ),
    );
  }

  ListView setListView() {
    return ListView.builder(
      itemCount: data == null ? 0 : data.length,
      itemBuilder: (context, index) {
        FBAPick tally = data[index];
        return Column(
          children: [
            Row(
              children: [
                Expanded(
                  flex: 2, //设置权重
                  child: GestureDetector(
                    onTap: () {
                      checkContainerNo(Utils.getStringisEmpty(tally.pickNo));
                    },
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          Utils.getStringisEmpty(tally.containerNo),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(color: MyAppTheme.color_333333, fontSize: 12.0),
                        ),
                        Text(
                          Utils.getStringisEmpty(tally.pickNo),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(color: MyAppTheme.color_666666, fontSize: 12.0),
                        ),
                      ],
                    ),
                  ),
                ),
                GestureDetector(
                  onTap: () {
                    fbaPickSchedule(Utils.getStringisEmpty(tally.pickNo));
                  },
                  child: Container(
                    padding: EdgeInsets.all(3),
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      color: MyAppTheme.nearlyBlue, // 背景颜色
                      borderRadius: BorderRadius.all(Radius.circular(5)), // 圆角半径
                      border: Border.all(
                        color: MyAppTheme.nearlyBlue, // 边框颜色
                        width: 0.5, // 边框宽度
                      ),
                    ),
                    child: Text(
                      'Complete',
                      style: MyAppTheme.captionWhite,
                    ), // 子控件，如果需要的话
                  ),
                )
              ],
            ),
            Divider(),
          ],
        );
      },
    );
  }

  void getContainerNoList() async {
    // 显示加载中对话框
    LoadingIndicator.show(context);

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.fbaPickPendingJobs);
    // 在需要的时候隐藏加载中对话框
    LoadingIndicator.hide();

    if (baseResponse.status == 200) {
      setState(() {
        data = baseResponse.data == null ? null : (new List<dynamic>.from(baseResponse.data).map((userJson) => FBAPick.fromJson(userJson)).toList());
      });
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  void checkContainerNo(String containerNo) async {
    // 显示加载中对话框
    LoadingIndicator.show(context);

    BaseResponse baseResponse = await NetworkManager().request(context, '${Constants.fbaPickInfo}/${containerNo}');
    // 在需要的时候隐藏加载中对话框
    LoadingIndicator.hide();

    if (baseResponse.status == 200) {
      setState(() {
        FBAPickInfo fbaPickInfo = FBAPickInfo.fromJson(baseResponse.data);
        Navigator.push(
          context,
          MaterialPageRoute(builder: (context) => FBAPickCategoryScreen(fbaPickInfo: fbaPickInfo)),
        ).then((value) => {
          if (value != null && value)
            {
              setState(() {
                getContainerNoList();
              })
            }
        });
      });
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  void fbaPickSchedule(String pickNo) async {
    updateHint('');
    // 显示加载中对话框
    LoadingIndicator.show(context);

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.fbaPickSchedule + "/" + pickNo);
    // hideDialogFunction();
    // 在需要的时候隐藏加载中对话框
    LoadingIndicator.hide();

    if (baseResponse.status == 200) {
      FBAPickSchedule fbaPickSchedule = FBAPickSchedule.fromJson(baseResponse.data);
      if (fbaPickSchedule == null) {
        return;
      }
      if ((fbaPickSchedule.picked == null) || (fbaPickSchedule.picked == 0)) {
        showDialog(
          context: context,
          builder: (context) => ShowDialogHint(hint: "At least one LPN has been scanned"),
        );
        return;
      }

      if ((fbaPickSchedule.pendingPick != null) && (fbaPickSchedule.pendingPick != 0)) {
        showDialog(
          context: context,
          builder: (context) => DataScheduleDialogHint(pickNo: pickNo, data: fbaPickSchedule),
        ).then((value) => {
              if (value != null && value) {fbaPickCompleted(pickNo)}
            });
        return;
      }

      fbaPickCompleted(pickNo);
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  void fbaPickCompleted(String pickNo) async {
    updateHint('');

    // 显示加载中对话框
    LoadingIndicator.show(context);

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.getLpnPhotoInfo + "/" + pickNo);
    // hideDialogFunction();
    // 在需要的时候隐藏加载中对话框
    LoadingIndicator.hide();

    if (baseResponse.status == 200) {
      getContainerNoList();
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  @override
  void showFileUploadData(String path, int type, int position, bool isSubmit) {
    // TODO: implement showFileUploadData
  }

  @override
  void setNext() {}

  @override
  void setReset() {
    setState(() {
      textEditingController.text = "";
      hint = "";
    });
  }
}

class DataScheduleDialogHint extends StatefulWidget {
  String pickNo;
  FBAPickSchedule data;

  DataScheduleDialogHint({this.pickNo, this.data});

  @override
  _DialogDataScheduleState createState() => _DialogDataScheduleState(pickNo: pickNo, data: data);
}

class _DialogDataScheduleState extends State<DataScheduleDialogHint> {
  String pickNo;
  FBAPickSchedule data;

  _DialogDataScheduleState({this.pickNo, this.data});

  @override
  Widget build(BuildContext context) {
    return Dialog(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12.0),
      ),
      child: Padding(
        padding: const EdgeInsets.only(top: 15, left: 15, right: 15),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            Text("Tips", style: MyAppTheme.title),
            SizedBox(height: 16.0),
            Text("Is lpn not fully processed (${Utils.getStringisInteger(data.picked)} / ${Utils.getStringisInteger(data.total)}), confirmed submitted?", style: MyAppTheme.text),
            SizedBox(height: 5.0),
            Row(
              children: <Widget>[
                Expanded(
                    flex: 1,
                    child: FlatButton(
                      child: Text(
                        'Close',
                        style: MyAppTheme.title,
                      ),
                      onPressed: () {
                        Navigator.of(context).pop();
                      },
                    )),
                Expanded(
                    flex: 1,
                    child: FlatButton(
                      child: Text(
                        'Confirm',
                        style: MyAppTheme.title,
                      ),
                      onPressed: () {
                        Navigator.of(context).pop(true);
                      },
                    )),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
